<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入查询的关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="员工名称" width="70">
			</el-table-column>
			<el-table-column prop="phone" label="员工电话" width="110">
			</el-table-column>
			<el-table-column prop="email" label="员工邮箱" width="120">
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="80" sortable>
			</el-table-column>
			<el-table-column label="员工状态" width="70" sortable>
        <template scope="s">
          <span style="color: #11b95c" v-if="s.row.state == 1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
			</el-table-column>
      <el-table-column label="所属部门" min-width="80" sortable>
        <template scope="s">
          <span v-if="s.row.department">{{s.row.department.name}}</span>
          <span style="color: #8c939d" v-else>无所属部门</span>
        </template>
      </el-table-column>
      <el-table-column label="员工性质" min-width="100" sortable>
        <template scope="s">
          <span v-if="s.row.shop_id">店铺管理员</span>
          <span style="color: #8c939d" v-else>平台管理员</span>
        </template>
      </el-table-column>
      <el-table-column prop="role_name" label="所属角色名" min-width="80" sortable>
      </el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
      <!-- 批量删除 -->
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!-- 分页栏 -->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :pageSize=this.pageSize :total=this.totals
                     :currentPage="this.currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="员工名称" prop="name">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="年龄">
					<el-input v-model="saveForm.age" :min="0" :max="200"></el-input>
				</el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio></el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门ID" label-width="100px" prop="department_id">
          <template>
            <!--
            下拉框的显示：
              v-for="item in managers" + 2个span
            回显机制：
              1.先根据v-model="saveForm.manager_id"中的manager_id从managers中找到回显哪一个对象
              2.但是对象中有很多属性，再通过:label="item.username" - 回显对象的username
            传值机制：
              1.当你选中某一个部门经理的时候，:value="item.id"  它会把选中对象的id
              2.赋值给v-model="saveForm.manager_id"中的manager_id
              3.saveForm对象中的其它值直接通过双向绑定赋值
            -->
            <el-select v-model="saveForm.department_id" placeholder="请选择">
              <el-option
                  v-for="item in departments"
                  :label="item.name"
                  :value="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="所属角色" label-width="100px" prop="department_id">
          <template>
            <el-select v-model="saveForm.role_id" placeholder="请选择">
              <el-option
                  v-for="item in roles"
                  :label="item.name"
                  :value="item.id">
                <span style="float: left">{{ item.name }}</span>
              </el-option>
            </el-select>
          </template>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, saveUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
			  //1.员工列表参数
        employees: [], //每页的数据
        totals: 0, //分页栏的计算数据
        currentPage : 1, //当前页
        pageSize: 5, //每页显示的条数
        //加载框默认不开启
        listLoading: false,

        //2.高级查询传递的参数
        keyword: '',

        //3.批量删除的参数
        sels: [],//列表选中列

        //4.添加和修改的数据
        title : '',
				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,
				saveFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
          phone: [
            { required: true, message: '请输入电话', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				saveForm: {
          id : null,
          username : '',
          phone : '',
          email : '',
          password : '',
          age : null,
          state : 1,
          department_id : null,
          role_id:null,
          role_name:''
				},
        //编辑界面下拉框中的数据
        departments : [],

        //角色下拉框中的数据
        roles:[]


			}
		},
		methods: {
      //1.获取用户列表
      getEmployees() {
        //请求参数
        let para = {
          pageSize: this.pageSize,
          currentPage : this.currentPage,
          keyword : this.keyword
        };
        //显示加载框
        this.listLoading = true;
        this.$http.post("/employee",para).then(res=>{
          this.employees = res.data.data;
          this.totals = res.data.totals;
          //隐藏加载框
          this.listLoading = false;
        }).catch(res=>{

        })
      },

      //2.页面改变，获取改变页的数据
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getEmployees();
      },

      //3.高级查询的方法
      keywordQuery(){
        this.currentPage = 1;
        this.getEmployees()
      },

      //4.删除功能
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {//确认框点确认走这
          //显示加载框
          this.listLoading = true;
          this.$http.delete("/employee/" + row.id).then(res=>{
            //隐藏加载框
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("删除成功！");
              //判断当前是否是最后一页的最后一条数据，如果是需要返回上一页
              let totalPage = Math.ceil(this.totals / this.pageSize);
              if(this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1){
                this.currentPage = this.currentPage - 1;
              }
              //重新加载当前页数据
              this.getEmployees();
            }else{
              //出现500的错误走这
              this.$message.error("请检查你的网络！！！");
            }
          }).catch(res=>{
            //出现400，404的错误走这
            this.$message.error("请检查你的网络！！！");
          })
        }).catch(() => {
          //确认框点取消走这
        });
      },

      //5.批量删除的逻辑
      //启用批量删除按钮
      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        //将参数中的每一个行对象的值都只保留id属性
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          //显示加载框
          this.listLoading = true;
          this.$http.patch("/employee",ids).then(res=>{
            //隐藏加载框
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("批量删除成功！");
              //批量删除成功之后返回第一页
              this.currentPage = 1;
              this.getEmployees();
            }else{
              //出现500的错误走这
              this.$message.error("请检查你的网络！！！");
            }
          }).catch(res=>{
            //出现400，404的错误走这
            this.$message.error("请检查你的网络！！！");
          })
        }).catch(() => {

        });
      },


      //6.修改和添加
      //显示编辑界面
      handleSave: function (index, row) {
        this.title = "修改";
        //显示修改的对话框
        this.saveFormVisible = true;
        //克隆对象，防止对话框中修改，分页栏数据跟着改变
        this.saveForm = Object.assign({}, row);
        //下拉框中的数据
        this.getDepartments();
        this.getRoles()
      },
      //显示新增界面
      handleAdd: function () {
        this.title = "增加";
        this.saveFormVisible = true;
        //下拉框中的数据
        this.getDepartments();
        this.getRoles()
        this.saveForm = {
          id : null,
          username : '',
          phone : '',
          email : '',
          password : '',
          age : null,
          state : 1,
          department_id : null,
          role_id:null
        };
      },
      //编辑
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              //显示加载框
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);
              this.$http.put("/employee",para).then(res=>{
                //关闭加载框
                this.saveLoading = false;
                if(res.data.success){
                  //关闭对话框
                  this.saveFormVisible = false;
                  this.$message.success("操作成功！");
                  this.getEmployees();
                }else{
                  //出现500的错误走这
                  this.$message.error("请检查你的网络！！！");
                }
              }).catch(res=>{
                //出现400，404的错误走这
                this.$message.error("请检查你的网络！！！");
              })
            });
          }
        });
      },
      getDepartments(){
        this.$http.get("/department").then(res=>{
          this.departments = res.data;
        })
      },
      getRoles(){
        this.$http.get("/role").then(res=>{
          this.roles = res.data;
        })
      },
    },




		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>